Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Builder pattern' - 2 code snippet(s) found

 Sample 1. Initialize object using Builder Pattern

public class Employee {
public String name;
public int age;
public int salary;

Employee withName(String name){
    this.name = name;
    return this;
}

Employee withAge(int age){
    this.age = age;
    return this;
}

Employee withSalary(int salary){
    this.salary = salary;
    return this;
}
}


public class BuilderPatternTest {
    public static void main(String[] args) {
       Employee employee = new Employee().withName("John").withAge(25).withSalary(10000);
    }
}

   Like      Feedback     builder design pattern  builder pattern


 Sample 2. Usage of Builder Class / Builder Pattern

public class BuggyBread {

   private String element1; // Make them private as it supports stronger encapsulation

   private String element2;

   private BuggyBread(String element1, String element2){ // Make it private so that it can only be used by Builder
      this.element1 = element1;
      this.element2 = element2;
   }

   public static class Builder {
      // Create Builder as nested class as its only supposed to Build BuggyBread objects,
      // Make it public so that it can be accessed from outside
      private String element1; // Make them private as it supports stronger encapsulation

      private String element2;

      Builder(){}; // We have to define this constructor if we need overloaded constructor too and need to initialize without arguments too

      Builder(BuggyBread buggybread){ // overloaded constructor to make things easy
         element1 = buggybread.element1;
         element2 = buggybread.element2;
      }

      Builder withElement1(String element1){ // Builder method to either populate elements or override ( if populated through overloaded constructor )
         this.element1 = element1;
         return this;
      }

      Builder withElement2(String element2){
         this.element2 = element2;
         return this;
      }

      BuggyBread build(){ // method to build BuggyBread object using final contents from Builder
         BuggyBread buggybread = new BuggyBread(element1,element2);
         return buggybread;
      }
   }
}

   Like      Feedback     builder pattern  builder class



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner